package com.heima.behavior.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.behavior.mapper.ApBehaviorEntryMapper;
import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApLikesBehavior;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ApBehaviorEntryServiceImpl implements ApBehaviorEntryService {
    @Autowired
    private MongoTemplate mongoTemplate;

    //查询行为实体
    @Override
    public ApBehaviorEntry findByUserIdOrEquipmentId(Integer userId, Integer equipmentId) {
        //非空判断
        if (userId != null) {
            //存在userId,优先使用userId查询
            Query query = Query.query(Criteria.where("entryId").is(userId));
            //查询
            ApBehaviorEntry apBehaviorEntry = mongoTemplate.findOne(query, ApBehaviorEntry.class);
            //非空判断
            if (apBehaviorEntry == null) {
                //当前用户没有行为实体数据,根据UserId创建一个
                apBehaviorEntry = new ApBehaviorEntry();
                apBehaviorEntry.setEntryId(userId);
                apBehaviorEntry.setType((short) 1);  //用户类型
                apBehaviorEntry.setCreatedTime(new Date());
                //将创建的行为实体对象保存到数据库
                mongoTemplate.save(apBehaviorEntry);
                //返回web层
                return apBehaviorEntry;
            }
            //当前用户有行为实体数据,直接返回给调用者
            return apBehaviorEntry;
        } else if (equipmentId != null) {
            //不存在用户id,使用设备id查询
            Query query = Query.query(Criteria.where("entryId").is(equipmentId));
            //查询
            ApBehaviorEntry apBehaviorEntry = mongoTemplate.findOne(query, ApBehaviorEntry.class);
            //非空判断
            if (apBehaviorEntry == null) {
                //当前用户没有行为实体数据,根据equipmentId创建一个
                apBehaviorEntry = new ApBehaviorEntry();
                apBehaviorEntry.setEntryId(equipmentId);
                apBehaviorEntry.setType((short) 0);  //终端设备类型
                apBehaviorEntry.setCreatedTime(new Date());
                //将创建的行为实体对象保存到数据库
                mongoTemplate.save(apBehaviorEntry);
                //返回web层
                return apBehaviorEntry;
            }
            return apBehaviorEntry;
        }
        return null;
    }
}
